# $Id: GDataClient.pm 2 2009-04-17 05:12:44Z hirotaka.ogawa $

package MT::Tool::MT2Blogger::GDataClient;
use strict;

use XML::Atom;
use base qw( XML::Atom::Client );

$XML::Atom::DefaultVersion = "1.0";

our $VERSION         = '0.01';
our $GOOGLE_AUTH_URL = 'https://www.google.com/accounts/ClientLogin';

sub service {
    my $client = shift;
    if (@_) {
        $client->{service} = shift;
        delete $client->{auth_token};    # drop auth_token if changing "service"
    }
    $client->{service};
}

sub login {
    my $client = shift;
    return $client->{auth_token} if $client->{auth_token};
    my $r = $client->{ua}->post(
        $GOOGLE_AUTH_URL,
        {
            Email   => $client->username,
            Passwd  => $client->password,
            source  => __PACKAGE__ . '-' . $VERSION,
            service => $client->service,
        }
    );
    return $client->error( "Error on GData ClientLogin: " . $r->status_line )
      unless $r->code == 200;
    my ($token) = $r->content =~ m/Auth=(.+)/;
    $client->{auth_token} = $token;
}

sub make_request {
    my $client = shift;
    my ($req) = @_;
    $client->login or return;    # do Google ClientLogin
    $client->munge_request($req);
    my $res = $client->{ua}->request($req);
    $client->munge_response($res);
    $client->{response} = $res;
    $res;
}

sub munge_request {
    my $client = shift;
    my ($req) = @_;
    $req->header( 'Authorization',
        'GoogleLogin auth=' . $client->{auth_token} );
    $req->content_type('application/atom+xml');
}

sub munge_responce { }

1;

=head1 NAME

MT::Tool::MT2Blogger::GDataClient - A GData wrapper for XML::Atom::Client

=head1 SYNOPSIS

    use MT::Tool::MT2Blogger::GDataClient;
    use XML::Atom::Entry;
    use XML::Atom::Person;

    my $api = MT::Tool::MT2Blogger::GDataClient->new;
    $api->username('Melody@gmail.com');
    $api->password('Nelson');
    $api->service('blogger');

    my $entry = XML::Atom::Entry->new;
    $entry->title('New Post');
    $entry->content('Content of my post.');

    my $author = XML::Atom::Person->new;
    $author->email('foo@example.com');
    $author->name('Foo Bar');
    $entry->author($author);

    my $editURI = $api->createEntry($postURI, $entry);

=head1 DESCRIPTION

I<MT::Tool::MT2Blogger::GDataClient> implements a Google Data API
client as a simple wrapper for I<XML::Atom::Client>.

=head1 USAGE

=head2 $api->service([ $servicename ])

If called with an argument, sets the service name, such as 'cl' or
'blogger', for Google ClientLogin service.

Returns the current service name that will be used when logging in to
the GData server.

=head1 AUTHOR

Hirotaka Ogawa E<lt>hirotaka.ogawa at gmail.comE<gt>

=cut
